import { defineStore } from 'pinia'
import apiClient, { initCSRF } from '../utils/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isAuthenticated: false
  }),

  actions: {
    async login(credentials) {
      await initCSRF() // 获取CSRF Token
      
      try {
        const response = await apiClient.post('/login', credentials)
        if (response.status === 200) {
          this.isAuthenticated = true
          await this.fetchUser()
        }
        return response
      } catch (error) {
        throw error.response.data
      }
    },

    async logout() {
      try {
        const response = await apiClient.post('/logout')
        if (response.status === 200) {
          this.$reset()
        }
        return response
      } catch (error) {
        throw error.response.data
      }
    },

    async fetchUser() {
      try {
        const response = await apiClient.get('/api/user')
        this.user = response.data
        this.isAuthenticated = true
        return response
      } catch (error) {
        this.$reset()
        throw error.response.data
      }
    }
  }
})